package com.alone.jpa.query.ext;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ArrayUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * hql格式化器
 *
 * @author Alone
 */
@Data
@AllArgsConstructor
public class HqlFormatter {

    public static  HqlFormatter of(String hqlTemp, Object... params) {
        return new HqlFormatter(hqlTemp, params);
    }

    private String hqlTemp;

    private Object[] params;

    /**
     * sqlTemp => id = {0} and name = {1} <p/>
     * params => {1, "小明"} <p/>
     * res => id = 1 and name = '小明'
     */
    public String format() {
        if (CharSequenceUtil.isBlank(hqlTemp)) {
            return null;
        }
        if (ArrayUtil.isNotEmpty(params)) {
            for (int i = 0; i < params.length; ++i) {
                final String target = StrPool.DELIM_START + i + StrPool.DELIM_END;
                Object param = params[i];
                String resolvedParam;
                // FIXME 目前支持 日期，字符串，数字类型，其他的估计得适配
                if (param instanceof Number) {
                    resolvedParam = param.toString();
                } else {
                    resolvedParam = "'" + param.toString() + "'";
                }
                hqlTemp = hqlTemp.replace(target, resolvedParam);
            }
        }
        return hqlTemp;
    }

}